/**
 * 获取监听的对象属性
 * @param {*} formPojo
 * @returns 监听的属性
 */
let pojo = {} // 表单对象
export function watchPropComputed(formPojo, subProp) {
      pojo = formPojo
      // 规则： #{属性名}=equity
      const condi = subProp.hideCondition
      if (condi) {
        var arrE = condi.match(/\${.*?\}|\#{.*?\}/g)
        for (const i of arrE) {
          if (i.startsWith('#{')) { // 取主表字段值
            const val = i.replace('#{', '').replace('}', '')
            return val
          }
        }
      }
}

 /**
  *
  * @returns 是否显示 （默认显示）
  */
export function judge(subTableProp) {
     let condi = subTableProp.hideCondition
     if (!condi) {
      return true
     }
     condi = condi.replaceAll(' ', '')
     const s = judgeDoOper(condi)
  //  console.log(replaceV(s), '字表是否显示', JSON.parse(JSON.stringify(pojo)))
    if (s) {
      return evil(replaceV(s))
    } else {
      return true
    }
}

function evil(fn) { // 计算值
  // console.log(fn, 'fn')
  const Fn = Function
  return new Fn('return ' + fn)()
}

function replaceV(eCondi) { // 替换值
  var arrE = eCondi.match(/\${.*?\}|\#{.*?\}/g)
  for (const i of arrE) {
    if (i.startsWith('#{')) { // 取主表字段值
      const val = i.replace('#{', '').replace('}', '')
      // console.log(pojo, pojo[val])
      if (!isNaN(pojo[val])) {
        eCondi = eCondi.replace(i, parseFloat(pojo[val]))
      } else {
        eCondi = eCondi.replace(i, `'${pojo[val]}'`)
      }
    } else if (i.startsWith('${')) {
      const val = i.replace('${', '').replace('}', '')
      let v2 = ''
      v2 = getUrlParm(val)
      if (v2 === undefined) {
        v2 = null
      }
      if (!isNaN(pojo[val])) {
        eCondi = eCondi.replace(i, parseFloat(v2))
      } else {
        eCondi = eCondi.replace(i, '`' + v2 + '`')
      }
    }
  }
  return eCondi
}
// 获取解析后的公式
function judgeDoOper(domains) {
  domains = JSON.parse(domains)
  let domin = ''
  if (!domains || Object.keys(domains[0]).length === 0) { // 默认对象有一个为空。。。
    return ''
  }
  domains.map((d, index) => {
    if (d) {
      domin += d.eField + d.eOper
      if (!isNaN(d.eCondi)) {
        domin += d.eCondi
      } else {
        domin += `'${d.eCondi}'`
      }
      if (index !== domains.length - 1) {
        domin += '&&'
      }
    }
  })
  return domin
}
/**
 *  获取url参数
 * @param {*} param
 * @returns
 */
function getUrlParm(param) {
  const url = window.location.href
  if (url.indexOf('?') !== -1) {
      const obj = {}
      const arr = url.slice(url.indexOf('?') + 1).split('&')
      arr.forEach(item => {
          const param = item.split('=')
          obj[param[0]] = param[1]
      })
        const val = obj[param]
        return val
  } else {
      return ''
    }
}
/**
 *  取路由  只支持一个条件 ${fundStatus}==TZ
 * @returns
 */
function expression(condi, i) {
  // console.log('condi', condi, i)
  if (!condi) {
      return true
  }
   if (condi.indexOf('==') !== -1 || condi.indexOf('!=') !== -1) {
      const val = i.replace('${', '').replace('}', '')
       const expree = condi.replace(i, `'${getUrlParm(val)}'`)
      return evil(expree)
   } else {
     // 历史数据
      let v1 = ''
      let v2 = ''
      v1 = condi.substring(condi.indexOf('=') + 1)
      i = i.replace('${', '').replace('}', '')
      v2 = getUrlParm(i)
      if (v2 === undefined) {
        v2 = null
      }
      if (v1 && v2) {
            return v1 === v2
      } else {
        return true
      }
   }
 }

 /**
  * 获取字段的默认值 （从后台返回的 如果包含有 ${路由值}）
  * 表单风格为--表单--的时候需要用得到
  */
 export function fieldDefaulfVal(fieldVal) {
    if (fieldVal) {
      fieldVal = fieldVal.replaceAll(' ', '')
      if (fieldVal.startsWith('${')) {
        const val = fieldVal.replace('${', '').replace('}', '')
        return getUrlParm(val)
      } else {
        return fieldVal
      }
    }
    return fieldVal
 }

  /**
  *
  *
  */
export function masterJudge(prop, pojo) {
  if (!prop) {
    return false
  }
    if (!prop.interExpress) {
      return true
    }
    // 根据 ‘||’ 或者 ‘&&’ 分组
    const groups = prop.interExpress.split(/[|||&]+/)
    // 结果集
    var outcome = []
    // 是否包含 ‘||’ / ‘&&’
    var orMoreover = prop.interExpress.includes('||')
    groups.forEach(formula => {
      let condi = formula
      condi = condi.replaceAll(' ', '')
      if (condi === '') {
        return true
      }
      var arrE = condi.match(/\${.*?\}|\#{.*?\}/g)
      var calcArr = ['>=', '<=', '!=']
      var calcSymbol = calcArr.includes(condi.substring(condi.lastIndexOf('}') + 1, condi.lastIndexOf('}') + 3)) ? condi.substring(condi.lastIndexOf('}') + 1, condi.lastIndexOf('}') + 3) : '=='
      var condiValue = condi.substring(condi.lastIndexOf('=') + 1)
      for (const i of arrE) {
        if (i.startsWith('${')) { // 取路由
          outcome.push(expression(condi, i))
        } else if (i.startsWith('#{')) { // 取主表字段值
          const val = i.replace('#{', '').replace('}', '')
          // 拼装表达式
          if (pojo[prop.key] && pojo[prop.key][val]) {
              outcome.push(evil(`\`${pojo[prop.key][val]}\`` + calcSymbol + `\`${condiValue}\``))
            // return pojo[prop.key][val] === condi.substring(condi.indexOf('=') + 1)
          } else if (!pojo[val]) {
            if (condi) {
              outcome.push(evil(`\`${pojo[val]}\`` + calcSymbol + `\`${condiValue}\``))
            }
            return true
          } else {
            outcome.push(evil(`\`${pojo[val]}\`` + calcSymbol + `\`${condiValue}\``))
            // return pojo[val] === condi.substring(condi.indexOf('=') + 1)
          }
        }
      }
    })
    if (outcome && outcome.length > 0) {
      console.log(orMoreover, outcome, 'orMoreover')
      if (outcome.length === 1 || orMoreover) {
        // 条件为 ‘||’
        return outcome.includes(true)
      } else {
        // 条件为 ‘&&’
        return !outcome.includes(false)
      }
    } else {
      return true
    }
}

export function subJudge(property) {
  if (!property) {
    return true
  }
  // console.log('property', property)
  property.forEach(prop => {
    let condi = prop.interExpress
    if (!condi) {
     return true
    }
    // console.log('pojo[prop.key]', pojo[prop.key])
    condi = condi.replaceAll(' ', '')
    var arrE = condi.match(/\${.*?\}|\#{.*?\}/g)
    for (const i of arrE) {
       if (i.startsWith('${')) { // 取路由
          return expression(condi, i)
       } else if (i.startsWith('#{')) { // 取主表字段值
           const val = i.replace('#{', '').replace('}', '')
           // 拼装表达式
           if (!pojo[val]) {
             return true
           } else if (pojo[prop.key] && pojo[prop.key][val]) {
             return pojo[prop.key][val] === condi.substring(condi.indexOf('=') + 1)
           } else {
             return pojo[val] === condi.substring(condi.indexOf('=') + 1)
           }
       }
    }
  })
  return true
}
export function watchMasterPropComputed(formPojo, subProp) {
  pojo = formPojo
  let val = 'un'
  for (const item of subProp) {
    const condi = item.interExpress
    if (condi) {
      var arrE = condi.match(/\${.*?\}|\#{.*?\}/g)
      for (const i of arrE) {
        if (i.startsWith('#{')) { // 取主表字段值
          val = i.replace('#{', '').replace('}', '')
          return val
        }
      }
    }
  }
}

/**
 *  深拷贝一个对象
 * @param {*} origin
 * @returns
 */
export const deepClone = function(origin) {
  if (origin === undefined) {
    return undefined
  }

  return JSON.parse(JSON.stringify(origin))
}
import axios from 'axios'
import { config as sysConfig } from '@/utils'
import { getToken } from '@/utils/auth'
/**
 * 表单配置请求接口公用方法
 * @param {*} dataSource  当前数据源配置
 * @param {*} testFlag
 * @param {*} $message el方法
 * @param {*} formModel  表单对象用于替换值获取值
 * @returns 成功的运行结果
 */
export async function runDataSourceRequest(dataSource, testFlag, $message, formModel, that) {
  try {
    const requestConfig = buildRequestConfig(dataSource, formModel, that)
    const result = await axios.request(requestConfig)
    // 成功请求的函数
    // const dhFn = new Function('result', 'testFlag', dataSource.dataSuccess)
    // eslint-disable-next-line no-useless-call
    if (result.data.code === 200 || testFlag) {
      // 将接口执行的数据返回，这里并不处理数据交给组件单独处理吧
      return result.data
    } else {
      const ehFn = new Function('error', '$message', dataSource.dataError)
      // eslint-disable-next-line no-useless-call
      ehFn.call(null, result.data, $message)
      return result.data
    }
  } catch (err) {
    // const ehFn = new Function('error', 'DSV', '$message', dataSource.dataError)
    //  // eslint-disable-next-line no-useless-call
    // ehFn.call(null, err, DSV, $message)
    console.error(err)
  }
}

function buildRequestConfig(dataSource, formModel, that) {
  const config = {}
  if (dataSource.rStyle === 'string') { // 固定 string  表达式 variable
    config.url = sysConfig.baseURL + dataSource.rUrl
  } else if (dataSource.rStyle === 'variable') {
    config.url = sysConfig.baseURL + initUrlParam(dataSource.rUrl, formModel, that)
  }
  config.method = dataSource.rMethod
  config.headers = assembleAxiosConfig(dataSource.rHead, formModel)
  config.headers['Authorization'] = 'Bearer ' + getToken()
  config.params = assembleAxiosConfig(dataSource.rParam, formModel)
  // 可能会有固定参数
  // config.data = assembleAxiosConfig(dataSource.data)
  return config
}
 /**
  * 组装axios请求配置参数
  * @param {*} arrayObj
  * @param {*} formModel
  * @returns
  */
export function assembleAxiosConfig(arrayObj, formModel) {
  // 数据库存放的结构为json串
  const result = {}
  if (!arrayObj || (arrayObj.length <= 0)) {
    return result
  }
  arrayObj = JSON.parse(arrayObj)
  arrayObj.map(ai => {
    let newVar = String(ai.value)
    if (newVar.startsWith('{') && newVar.endsWith('}')) {
        // 字符串变量 遵循着{*}格式
        newVar = newVar.replace(/[{}]/g, '')
        // 从当前表单对象获取值，这里有个问题可能获取不到表单对象的值
        newVar = formModel[newVar]
    }
    // 目前只有字符串 后面可能会加其他需求
    result[ai.name] = newVar
  })
  return result
}
/**
 * 替换url
 */
function initUrlParam(url, formModel, that) { // 返回新的url
  // 变量表达式规则 {*}
  //  const regex = /{(\w+)(?:\.(\w+))?}/g
    const regex = /[$]?{(\w+)(?:\.(\w+))?}/g
   const newUrl = url.replace(regex, (match, tableName, key) => {
    if (match.startsWith('${') && match.endsWith('}')) {
      const routerParam = match.replace(/[${}]/g, '')
       return that.$route.query[routerParam]
    } else {
      if (key) {
        return formModel[tableName][key]
      } else {
        return formModel[tableName]
      }
    }
   })
   return newUrl
}

/**
 * 根据条件展示分组
 * @param condition 条件
 */
export function showGroup(condition, pojo) {
  if (!condition) {
    return true
  }
  var condis = condition.split(';')
  var field = condis[0]
  var cond = condis[1]
  var value = condis[2]
  if (field.startsWith('${')) {
    // 路由获取
    const val = field.replace('${', '').replace('}', '')
    var value2 = getUrlParm(val)
    const express = `\`${value}\`` + cond + `\`${value2 }\``
    return evil(express)
  } else if (field.startsWith('#{')) {
    // 表字段获取
    const val = field.replace('#{', '').replace('}', '')
    const express = `\`${pojo[val] }\`` + cond + `\`${value }\``
    // console.log(val, '条件')
    return evil(express)
  }
  return true
}
